package com.youdianstar.app.ui.reward

import android.app.Dialog
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import com.gyf.immersionbar.ImmersionBar
import com.safframework.eventbus.EventBus
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.UserInfo
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.LanguageConfig
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.util.Tool
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.ActivityInviteBinding
import com.youdianstar.app.entity.InviteInfo
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.WalletDialogUtil
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.util.SpanUtil
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: InviteActivity
 * Author: 82149 Create: 2023/7/29 18:50
 * Changes (from 2023/7/29)
 * --------------------------------------------------
 * description: 邀请页面
 * ---------------------------------------------------
 *
 */
class InviteActivity :BaseActivity<ActivityInviteBinding, RewardViewModel>(){
    override fun layoutId(): Int = R.layout.activity_invite

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): RewardViewModel {
        val model: RewardViewModel by viewModel()
        return model
    }

    private val mHandler = Handler(Looper.myLooper()!!)
    private var user : UserInfo?=null
    private var ruleList = mutableListOf<InviteInfo>()
    private var ruleSheetDialog: Dialog? = null
    private var inviteCode = ""

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null && isShouldHideKeyBord(view, ev)) {
                this.hideSoftInput(view.windowToken)
                try {
                    mBinding.edtInput.clearFocus()
                } catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun initData() {
        super.initData()
        mBinding.headBar.initTitle(this, title = getString(R.string.invite_referral))
        mBinding.headBar.setRightText(getString(R.string.invite_referralRecord), R.color.color_9BB955) {
            //邀请记录
            startActivity<InviteRecordActivity>()
        }
        val titlePart1 = getString(R.string.invite_inviteTitle1)
        val titlePart2 = getString(R.string.invite_inviteTitle2)
        SpanUtil.create()
            .addSection("$titlePart1 $titlePart2")
            .setForeColor(titlePart1, getViewColor(this, R.color.color_999999))
            .setTypeface(titlePart1, "sans-serif-medium")
            .setForeColor(titlePart2, getViewColor(this, R.color.color_39404D))
            .setTypeface(titlePart2, "sans-serif-black")
            .showIn(mBinding.txInviteNotify)
        ImmersionBar.with(this).keyboardEnable(true).init()

        user = DataAppManager.instance.getUser()
        user?.let {
            inviteCode = it.inviteCode
            mBinding.tvInviteCode.text = it.inviteCode
        }

        mBinding.btnSave.isEnabled = false

        EventBus.post(BusEntity(DataCode.CLOSE_DRAWER))//关闭侧边栏
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.redeemInviteResultData.observe(this,object : BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                //兑换邀请码结果
                mHandler.postDelayed({
                    dismissDialog()
                    toastShow(getString(R.string.public_success))
                    mBinding.edtInput.setText("")
                    mBinding.btnSave.isClickable = true
                },2000L)
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                mBinding.btnSave.isClickable = true
            }
        })

        mViewModel.invitePlansLiveData.observe(this, object :BaseApiResultObserver<List<InviteInfo>>(){
            override fun onDataResult(data: List<InviteInfo>?) {
                super.onDataResult(data)
                dismissDialog()
                ruleList.clear()
                data?.let { resList ->
                    ruleList.addAll(resList)
                }
                //显示弹框
                showInvitationRuleSheet()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    override fun initClickEvent() {
        mBinding.edtInput.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                mBinding.btnSave.isEnabled = (s.toString().isNotEmpty() && s.toString().length>=8)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })

        mBinding.tvAbout.setThrottleListener {
            //邀请规则 弹框
            if (ruleList.isEmpty()){
                mViewModel.getInvitePlans()
            }else{
                showInvitationRuleSheet()
            }
        }

        mBinding.clShareAndInvite.setThrottleListener {
            //分享
            user?.let {
                val shareStr = getString(R.string.invite_inviteFriend)
                val linkBaseTx = DataAppManager.instance.getConfig(ConfigKey.INVITE_LINK)
                val codeTx = "?invitefriend="+it.inviteCode
                val abb = "&lang=" + LanguageConfig.instance.getLanguageCode()
                val urlTx = Uri.parse("$linkBaseTx$codeTx$abb").toString()
                LogUtil.i("---link: $urlTx")
                Tool.shareInvite(this, "$shareStr $urlTx")
            }
        }

        mBinding.tvInviteCode.setThrottleListener {
            val codeText = mBinding.tvInviteCode.text.toString()
            if (!StrUtil.isEmpty(codeText)){
                Tool.copy(this,codeText)
                toastShow(getString(R.string.invite_copied))
            }
        }

        mBinding.btnSave.setThrottleListener {
            val inputCode = mBinding.edtInput.text.toString()
            if (inputCode.length<8){
                toastShow(getString(R.string.toast_validInviteCode))
                return@setThrottleListener
            }
            val userCode = user?.inviteCode?:""
            if (inputCode == userCode){
                toastShow(getString(R.string.invite_inviteSelfErr))
                return@setThrottleListener
            }
            mBinding.btnSave.isClickable = false
            mViewModel.redeemInvitationCode(inputCode)
        }
    }

    private fun showInvitationRuleSheet(){
        ruleSheetDialog?.dismiss()
        ruleSheetDialog = WalletDialogUtil.instance.sheetRedeemInvitationRule(this, ruleList)
    }

    override fun onDestroy() {
        ruleSheetDialog?.dismiss()
        super.onDestroy()
    }
}